package com.nanxhs.structure;

import java.lang.reflect.Array;

/**
 * 栈实现
 * @author 唐海斌
 * @version 1.0
 * @date 2021/5/19 11:17
 */
public class Stack<T> {
    /**
     * 初始化大小
     */
    private static final int INIT_ARRAY_SIZE = 10;
    /**
     * 栈游标指针，指示当前最新数据的下标
     */
    private int point = -1;
    /**
     * 栈中元素的类型
     */
    private Class<T> clazz;
    /**
     * 元素容器
     */
    private T[] stack;

    public Stack(Class<T> clazz) {
        stack = (T[]) Array.newInstance(clazz, INIT_ARRAY_SIZE);
        this.clazz = clazz;
    }

    /**
     * 入栈
     * @param element
     */
    public void push(T element) {
        if (element == null) {
            throw new RuntimeException("element not null");
        }
        if (++point == length() - 1) {
            dilatation();
        }
        stack[point] = element;
    }

    /**
     * 出栈
     * @return
     */
    public T pop() {
        if (point < 0) {
            return null;
        }
        return stack[point--];
    }

    /**
     * 清空栈
     */
    public void clear() {
        while (point > -1) {
            pop();
        }
    }

    /**
     * 栈的当前容量
     * @return
     */
    public int length() {
        return stack.length;
    }

    /**
     * 栈元素数量
     * @return
     */
    public int count() {
        return point + 1;
    }

    /**
     * 动态扩容
     */
    private void dilatation() {
        T[] newStack = (T[]) Array.newInstance(clazz, length() * 2);
        for (int index = 0; index < stack.length; ++index) {
            newStack[index] = stack[index];
        }
        stack = newStack;
    }
}
